﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;

namespace GrayParrot.Caching
{
    /// <summary>
    /// Singleton Cache Helper...
    /// </summary>
    /// <remarks>
    /// Centralized the creation of a cache object instance.
    /// I use Unity for IOC and Register by convention to register the ICache object instance and resolve it.
    /// Do not need of any configuration for Unity to work.
    /// </remarks>
    public sealed class CacheHelper
    {
        private static readonly Lazy<CacheHelper> lazy =
            new Lazy<CacheHelper>(() => new CacheHelper());

        public static CacheHelper Instance { get { return lazy.Value; } }

        private CacheHelper()
        {
        }

        private ICache m_internalInstance = null;

        public ICache GetCache()
        {
            if (m_internalInstance == null)
            {
                using (var container = new UnityContainer())
                {
                    container.RegisterTypes(AllClasses.FromAssembliesInBasePath(),
                                            WithMappings.FromMatchingInterface,
                                            WithName.Default,
                                            WithLifetime.ContainerControlled);

                    m_internalInstance = container.Resolve<ICache>();
                }
            }

            return m_internalInstance;
        }
    } 
}
